package io.nads.interceptor;

import io.nads.context.BaseContext;
import io.nads.dto.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class AuthLoginInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Long currentId = BaseContext.getCurrentId();
        
        if (currentId == null) {
            log.warn("用户未登录，拒绝访问接口: {}", request.getRequestURI());
            
            // 设置响应状态码和内容类型
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            
            // 返回统一的错误响应
            Result errorResult = Result.fail("用户未登录，请先登录");
            String jsonResponse = objectMapper.writeValueAsString(errorResult);
            
            try {
                response.getWriter().write(jsonResponse);
                response.getWriter().flush();
            } catch (IOException e) {
                log.error("写入响应失败: {}", e.getMessage(), e);
            }
            
            return false;
        }
        
        log.debug("用户认证通过，用户ID: {}, 访问接口: {}", currentId, request.getRequestURI());
        return true;
    }
}
